import React, { useState, useEffect } from "react";
import { Button, Modal, Input, Cascader, Form, Row, Col, message, Checkbox, Table, Popconfirm, Spin, Upload } from "antd";
import {
    PlusOutlined,
    CloseOutlined,
    DeleteOutlined,
    SearchOutlined,
    EditOutlined,
    InboxOutlined,
    ControlOutlined
} from "@ant-design/icons";
import { createParameter, getParameters, updateParameter, deleteParameter } from '../../../services/parameterService';
import Search from "antd/es/input/Search";
import '../index.scss'

// 定义级联选择的数据结构
const dataTypeOptions = [
    {
        value: 'array',
        label: 'Array',
        children: [
            {
                value: 'array-integer',
                label: 'Integer',
            },
            {
                value: 'array-double',
                label: 'Double',
            },
            {
                value: 'array-string',
                label: 'String',
            },
            {
                value: 'array-boolean',
                label: 'Boolean',
            },
            {
                value: 'array-file',
                label: 'File',
            },
        ],
    },
    {
        value: 'integer',
        label: 'Integer',
    },
    {
        value: 'double',
        label: 'Double',
    },
    {
        value: 'string',
        label: 'String',
    },
    {
        value: 'boolean',
        label: 'Boolean',
    },
    {
        value: 'file',
        label: 'File',
    },
];

const { Dragger } = Upload;

const ParameterManagement = () => {
    const [parameters, setParameters] = useState([]);
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [editingParam, setEditingParam] = useState(null);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [form] = Form.useForm();
    const [continueCreate, setContinueCreate] = useState(false);
    const [arrayDefaultValues, setArrayDefaultValues] = useState([]);
    const [isEditMode, setIsEditMode] = useState(false);
    const [loading, setLoading] = useState(false);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [uploadedFiles, setUploadedFiles] = useState([]); // 存储上传的文件

    // 获取参数列表
    useEffect(() => {
        fetchParameters();
    }, []);

    // 监听编辑参数变化
    useEffect(() => {
        if (editingParam) {
            setIsModalOpen(true);
            setIsEditMode(true);
            // 处理数据类型格式
            let dataType = editingParam.type;
            let dataTypeArray = [dataType];

            if (dataType.startsWith('array-')) {
                dataTypeArray = ['array', dataType];
                // 处理数组默认值
                const values = Array.isArray(editingParam.defaultValue)
                    ? editingParam.defaultValue
                    : [editingParam.defaultValue];
                setArrayDefaultValues(values);

                // 如果是文件数组，设置上传的文件
                if (dataType === 'array-file') {
                    setUploadedFiles(values.map(file => ({
                        uid: file.uid || `file-${Date.now()}`,
                        name: file.name,
                        status: 'done',
                        url: file.url
                    })));
                }
            } else {
                setArrayDefaultValues([]);

                // 如果是单个文件，设置上传的文件
                if (dataType === 'file' && editingParam.defaultValue) {
                    setUploadedFiles([{
                        uid: editingParam.defaultValue.uid || `file-${Date.now()}`,
                        name: editingParam.defaultValue.name,
                        status: 'done',
                        url: editingParam.defaultValue.url
                    }]);
                } else {
                    setUploadedFiles([]);
                }
            }

            form.setFieldsValue({
                parameterName: editingParam.name,
                dataType: dataTypeArray,
                defaultValue: editingParam.defaultValue,
                description: editingParam.description,
                unit: editingParam.unit || ''
            });
        } else {
            setIsEditMode(false);
            form.resetFields();
            setArrayDefaultValues([]);
            setUploadedFiles([]);
        }
    }, [editingParam, form]);

    // 数据类型变化时重置默认值
    const handleDataTypeChange = (value) => {
        const selectedType = value ? value[value.length - 1] : '';

        // 清除所有表单字段的默认值
        const fieldsToReset = {};
        if (selectedType.startsWith('array-')) {
            // 对于数组类型，清除所有数组输入框
            for (let i = 0; i < arrayDefaultValues.length; i++) {
                fieldsToReset[`defaultValue[${i}]`] = undefined;
            }
        } else {
            // 对于非数组类型，清除单个默认值
            fieldsToReset['defaultValue'] = undefined;
        }

        // 重置表单字段
        form.setFieldsValue(fieldsToReset);

        // 初始化数组类型的默认值输入框
        if (selectedType.startsWith('array-') && selectedType !== 'array-file') {
            setArrayDefaultValues(['']); // 初始显示一个输入框
        } else {
            setArrayDefaultValues([]);
        }

        setUploadedFiles([]);
    };

    // 添加数组默认值输入
    const addDefaultValueInput = () => {
        const newCount = arrayDefaultValues.length + 1;
        setArrayDefaultValues([...arrayDefaultValues, '']);

        // 清除新输入框对应表单字段的值
        form.setFieldsValue({
            [`defaultValue[${newCount - 1}]`]: undefined
        });
    };

    // 移除数组默认值输入
    const removeDefaultValueInput = (index) => {
        const newValues = [...arrayDefaultValues];
        newValues.splice(index, 1);
        setArrayDefaultValues(newValues);
    };

    // 更新数组默认值
    const handleArrayValueChange = (index, value) => {
        const newValues = [...arrayDefaultValues];
        newValues[index] = value;
        setArrayDefaultValues(newValues);
    };

    // 处理文件上传
    const handleFileChange = (info) => {
        let fileList = [...info.fileList];

        // 限制文件数量为1（非数组文件类型）
        const dataType = form.getFieldValue('dataType');
        const selectedType = dataType ? dataType[dataType.length - 1] : '';

        if (selectedType === 'file') {
            fileList = fileList.slice(-1); // 只保留最后一个文件
        }

        setUploadedFiles(fileList);

        // 处理上传状态
        const status = info.file.status;
        if (status !== 'uploading') {
            console.log(info.file, info.fileList);
        }
        if (status === 'done') {
            message.success(`${info.file.name} 文件上传成功`);
        } else if (status === 'error') {
            message.error(`${info.file.name} 文件上传失败`);
        }
    };

    // 自定义上传请求
    const customRequest = ({ file, onSuccess, onError }) => {
        // 模拟上传，实际项目中应替换为真实的上传API
        setTimeout(() => {
            onSuccess({
                url: `https://picsum.photos/200/300?random=${Math.random()}`,
                name: file.name,
                uid: file.uid
            });
        }, 1000);
    };

    const handleSearch = () => {
        message.warning('搜索功能待开发');
    };

    // 获取参数列表（异步处理）
    const fetchParameters = async () => {
        try {
            setLoading(true);
            const params = await getParameters();
            console.log("参数数据：", params);
            setParameters(params);
        } catch (error) {
            message.error('获取参数列表失败');
            console.error('获取参数列表错误:', error);
        } finally {
            setLoading(false);
        }
    };

    // 处理添加参数
    const handleAddParameter = () => {
        setIsModalOpen(true);
        setIsEditMode(false);
        form.resetFields();
        setArrayDefaultValues([]);
        setUploadedFiles([]);
    };

    // 处理表单提交
    const handleOk = async () => {
        try {
            setIsSubmitting(true);
            const values = await form.validateFields();

            // 处理数据类型
            let type = values.dataType[values.dataType.length - 1];

            // 处理默认值
            let defaultValue;
            if (type.startsWith('array-')) {
                // 过滤空值
                if (type === 'array-file') {
                    // 处理文件数组
                    defaultValue = uploadedFiles.map(file => ({
                        name: file.name,
                        url: file.response?.url || file.url,
                        uid: file.uid
                    }));

                    if (defaultValue.length === 0) {
                        throw new Error('请上传至少一个文件');
                    }
                } else {
                    // 处理其他数组类型
                    defaultValue = arrayDefaultValues.filter(value => value !== '');
                    if (defaultValue.length === 0) {
                        throw new Error('数组默认值不能为空');
                    }
                }
            } else {
                if (type === 'file') {
                    // 处理单个文件
                    if (uploadedFiles.length === 0) {
                        throw new Error('请上传文件');
                    }
                    defaultValue = {
                        name: uploadedFiles[0].name,
                        url: uploadedFiles[0].response?.url || uploadedFiles[0].url,
                        uid: uploadedFiles[0].uid
                    };
                } else {
                    // 处理其他类型
                    defaultValue = values.defaultValue;
                }
            }

            // 创建参数对象
            const paramData = {
                name: values.parameterName,
                defaultValue: defaultValue,
                type: type,
                description: values.description,
                unit: values.unit || ''
            };

            // 根据是否为编辑模式选择不同的API
            if (isEditMode && editingParam && editingParam.id) {
                // 编辑模式
                await updateParameter(editingParam.id, paramData);
                message.success('更新成功');
            } else {
                // 新建模式
                await createParameter(paramData);
                message.success('创建成功');
            }

            // 刷新数据
            fetchParameters();

            if (!continueCreate || isEditMode) {
                setIsModalOpen(false);
                setEditingParam(null);
            }

            if (!isEditMode) {
                form.resetFields();
                setArrayDefaultValues([]);
                setUploadedFiles([]);
            }
        } catch (error) {
            if (error instanceof Error) {
                message.error(error.message);
            } else {
                message.error('操作失败');
            }
            console.log('验证失败:', error);
        } finally {
            setIsSubmitting(false);
        }
    };

    // 处理取消
    const handleCancel = () => {
        setIsModalOpen(false);
        form.resetFields();
        setArrayDefaultValues([]);
        setUploadedFiles([]);
        setEditingParam(null);
    };

    // 处理删除
    const handleDelete = async (id) => {
        try {
            await deleteParameter(id);
            fetchParameters();
            message.success('删除成功');
        } catch (error) {
            message.error('删除失败');
            console.error('删除参数错误:', error);
        }
    };

    // 批量删除
    const handleBatchDelete = () => {
        if (selectedRowKeys.length === 0) {
            message.warning('请选择要删除的参数');
            return;
        }

        // 获取参数名
        const selectedParams = parameters.filter(param => selectedRowKeys.includes(param.id));
        const selectedNames = selectedParams.map(param => param.name).join(', ');

        Modal.confirm({
            title: '删除确认',
            content: (
                <div>
                    <p>确定要删除以下{selectedRowKeys.length}个参数吗？</p>
                    {selectedNames.length < 20 ? (
                        <p><strong>{selectedNames}</strong></p>
                    ) : (
                        <p>已选择{selectedRowKeys.length}个参数</p>
                    )}
                </div>
            ),
            okText: '确定删除',
            okType: 'danger',
            cancelText: '取消',
            onOk: async () => {
                try {
                    for (const id of selectedRowKeys) {
                        await deleteParameter(id);
                    }
                    fetchParameters();
                    setSelectedRowKeys([]);
                    message.success('批量删除成功');
                } catch (error) {
                    message.error('批量删除失败');
                    console.error('批量删除错误:', error);
                }
            }
        });
    };

    // 表格行选择变化
    const onSelectChange = (newSelectedRowKeys) => {
        setSelectedRowKeys(newSelectedRowKeys);
    };

    // 渲染默认值（支持文件预览）
    const renderDefaultValue = (value) => {
        if (!value) return '-';

        if (Array.isArray(value)) {
            if (value.length === 0) return '-';

            // 检查是否是文件数组
            if (value[0].url) {
                return (
                    <div className="file-list">
                        {value.map((file, index) => (
                            <div key={index} className="file-item">
                                <a href={file.url} target="_blank" rel="noopener noreferrer">
                                    <i className="fa fa-file-o mr-2" />{file.name}
                                </a>
                            </div>
                        ))}
                    </div>
                );
            }

            return value.join(', ');
        }

        // 检查是否是单个文件
        if (value.url) {
            return (
                <div className="file-item">
                    <a href={value.url} target="_blank" rel="noopener noreferrer">
                        <i className="fa fa-file-o mr-2" />{value.name}
                    </a>
                </div>
            );
        }

        return value;
    };

    const columns = [
        {
            title: '序号',
            dataIndex: 'id',
            key: 'id',
            align: 'center',
            render: (text, record, index) => index + 1
        },
        {
            title: '参数名称',
            dataIndex: 'name',
            key: 'name',
            align: 'center'
        },
        {
            title: '默认值',
            dataIndex: 'defaultValue',
            key: 'defaultValue',
            align: 'center',
            render: renderDefaultValue
        },
        {
            title: '类型',
            dataIndex: 'type',
            key: 'type',
            align: 'center'
        },
        {
            title: '描述',
            dataIndex: 'description',
            key: 'description',
            align: 'center'
        },
        {
            title: '操作',
            key: 'action',
            align: 'center',
            fixed: 'right',
            render: (_, record) => (
                <span>
                    <Button type="text" style={{ color: '#1677FF' }} icon={<EditOutlined />} onClick={() => setEditingParam(record)}>
                    </Button>
                    <Popconfirm
                        title="确定要删除吗？"
                        onConfirm={() => handleDelete(record.id)}
                        okText="确定"
                        cancelText="取消"
                    >
                        <Button danger type="text" icon={<DeleteOutlined />}>
                        </Button>
                    </Popconfirm>
                </span>
            ),
        },
    ];

    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
        getCheckboxProps: (record) => ({
            key: record.id
        })
    };

    return (
        <div className="parameter-management-container">
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
                <Search
                    enterButton={<SearchOutlined />}
                    onSearch={handleSearch}
                    allowClear
                    placeholder="请输入搜索内容"
                    style={{ width: 250 }}
                />
                <div style={{ marginLeft: 20 }}>
                    <Button
                        danger
                        icon={<DeleteOutlined />}
                        onClick={handleBatchDelete}
                        disabled={selectedRowKeys.length === 0}
                    >
                        批量删除
                    </Button>
                    <Button
                        icon={<PlusOutlined />}
                        onClick={handleAddParameter}
                        type="primary"
                        style={{ marginLeft: 10 }}
                    >
                        新建参数
                    </Button>
                </div>
            </div>

            <Spin spinning={loading}>
                <Table
                    columns={columns}
                    dataSource={parameters}
                    style={{ marginTop: 10 }}
                    pagination={{
                        total: parameters.length,
                        showTotal: (total) => `共 ${total} 条`,
                        showSizeChanger: true,
                        pageSizeOptions: ['5', '10', '20', '50']
                    }}
                    rowSelection={rowSelection}
                    rowKey="id"
                    scroll={{
                        x: 'max-content',
                        y: 80*5
                    }}
                />
            </Spin>

            {/* 添加/编辑参数模态框 */}
            <Modal
                title={isEditMode ? "编辑参数" : "新建参数"}
                open={isModalOpen}
                onOk={handleOk}
                onCancel={handleCancel}
                okText={isEditMode ? "保存" : "确定"}
                cancelText="取消"
                width={700}
                confirmLoading={isSubmitting}
                footer={[
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', width: '100%' }}>
                        {!isEditMode && (
                            <Checkbox
                                checked={continueCreate}
                                onChange={(e) => setContinueCreate(e.target.checked)}
                            >
                                继续新建下一个参数
                            </Checkbox>
                        )}
                        <div>
                            <Button key="back" style={{ marginRight: 20 }} onClick={handleCancel}>
                                取消
                            </Button>
                            <Button key="submit" type="primary" onClick={handleOk} loading={isSubmitting}>
                                {isEditMode ? "保存" : "确定"}
                            </Button>
                        </div>
                    </div>
                ]}
            >
                <Form form={form} layout="vertical" initialValues={{ dataType: ["integer"] }}>
                    <Row gutter={[16, 16]}>
                        <Col span={14}>
                            <Form.Item
                                name="parameterName"
                                label="参数名称"
                                rules={[{ required: true, message: '请输入参数名称' }]}
                            >
                                <Input prefix={<ControlOutlined style={{ fontSize: 20, marginRight: 5, color:'#1677FF' }}/>} maxLength={30} placeholder="请输入参数名称" />
                            </Form.Item>
                            <Form.Item
                                name="description"
                                label="描述信息"
                            >
                                <Input.TextArea
                                    maxLength={200}
                                    style={{ height: 210 }}
                                    placeholder="请输入描述信息"
                                    rows={3}
                                />
                            </Form.Item>
                        </Col>
                        <Col span={10}>
                            <Form.Item
                                name="dataType"
                                label="数据类型"
                                rules={[{ required: true, message: '请选择数据类型' }]}
                            >
                                <Cascader
                                    expandTrigger="hover"
                                    options={dataTypeOptions}
                                    placeholder="请选择数据类型"
                                    onChange={handleDataTypeChange}
                                />
                            </Form.Item>

                            <Form.Item
                                noStyle
                                shouldUpdate={(prevValues, currentValues) => prevValues.dataType !== currentValues.dataType}
                            >
                                {({ getFieldValue }) => {
                                    const dataType = getFieldValue('dataType');
                                    const selectedType = dataType ? dataType[dataType.length - 1] : '';

                                    // 处理文件类型
                                    if (selectedType === 'file' || selectedType === 'array-file') {
                                        const isMultiple = selectedType === 'array-file';

                                        return (
                                            <Form.Item
                                                name="defaultValue"
                                                label={selectedType === 'file' ? '文件上传' : '多文件上传'}
                                                rules={[{ required: true, message: '请上传文件' }]}
                                            >
                                                <Dragger
                                                    name="file"
                                                    multiple={isMultiple}
                                                    fileList={uploadedFiles}
                                                    onChange={handleFileChange}
                                                    customRequest={customRequest}
                                                    accept=".jpg,.png,.pdf,.doc,.docx,.xls,.xlsx,.txt"
                                                >
                                                    <p className="ant-upload-drag-icon">
                                                        <InboxOutlined />
                                                    </p>
                                                    <p className="ant-upload-text">点击或拖拽文件到此处上传</p>
                                                    <p className="ant-upload-hint">
                                                        {isMultiple ? '支持上传多个文件' : '仅支持上传单个文件'}
                                                    </p>
                                                </Dragger>
                                            </Form.Item>
                                        );
                                    }

                                    // 处理数组类型的默认值输入
                                    if (selectedType.startsWith('array-')) {
                                        const baseType = selectedType.replace('array-', '');
                                        return (
                                            <>
                                                {arrayDefaultValues.map((value, index) => (
                                                    <div key={index} style={{ display: 'flex', marginBottom: 0 }}>
                                                        <Form.Item
                                                            style={{ flex: 1 }}
                                                            name={`defaultValue[${index}]`}
                                                            label={index === 0 ? `数组默认值 (${baseType})` : ''}
                                                            rules={[
                                                                { required: true, message: `请输入${baseType}类型值` },
                                                                (baseType === 'integer' || baseType === 'double') ? {
                                                                    validator: (_, value) => {
                                                                        if (!value || /^-?\d+(\.\d+)?$/.test(value)) {
                                                                            return Promise.resolve();
                                                                        }
                                                                        return Promise.reject(new Error(`请输入有效的${baseType}类型值`));
                                                                    }
                                                                } : {}
                                                            ].filter(Boolean)}
                                                        >
                                                            <Input
                                                                maxLength={30}
                                                                showCount
                                                                placeholder={`请输入${baseType}类型值`}
                                                                value={value}
                                                                onChange={(e) => handleArrayValueChange(index, e.target.value)}
                                                            />
                                                        </Form.Item>
                                                        {index > 0 && (
                                                            <Button danger type="link" icon={<CloseOutlined />} onClick={() => removeDefaultValueInput(index)} />
                                                        )}
                                                    </div>
                                                ))}
                                                <Button type="dashed" icon={<PlusOutlined />} style={{ width: '100%', marginBottom: 5 }} onClick={addDefaultValueInput}>
                                                    添加默认值
                                                </Button>

                                                {(baseType === 'integer' || baseType === 'double') && (
                                                    <Form.Item
                                                        name="unit"
                                                        label="单位"
                                                    >
                                                        <Input maxLength={30} placeholder="请输入单位" />
                                                    </Form.Item>
                                                )}
                                            </>
                                        );
                                    }

                                    // 处理普通类型的默认值输入
                                    return (
                                        <>
                                            <Form.Item
                                                name="defaultValue"
                                                label="默认值"
                                                rules={[
                                                    { required: true, message: `请输入${selectedType}类型默认值` },
                                                    (selectedType === 'integer' || selectedType === 'double') ? {
                                                        validator: (_, value) => {
                                                            if (!value || /^-?\d+(\.\d+)?$/.test(value)) {
                                                                return Promise.resolve();
                                                            }
                                                            return Promise.reject(new Error(`请输入有效的${selectedType}类型值`));
                                                        }
                                                    } : {}
                                                ].filter(Boolean)}
                                            >
                                                <Input maxLength={30} placeholder={`请输入${selectedType}类型默认值`} />
                                            </Form.Item>

                                            {(selectedType === 'integer' || selectedType === 'double') && (
                                                <Form.Item
                                                    name="unit"
                                                    label="单位"
                                                >
                                                    <Input maxLength={30} placeholder="请输入单位" />
                                                </Form.Item>
                                            )}
                                        </>
                                    );
                                }}
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </Modal>
        </div>
    );
};

export default ParameterManagement;